const { ipcMain } = require('electron');
const { getMainKnex } = require('../database/knex');

function registerConfigHandlers() {
    const knex = getMainKnex();

    // Save analyzer profile
    ipcMain.handle('config:save-profile', async (event, { name, configs, description }) => {
        try {
            const existing = await knex('analyzer_profiles').where('name', name).first();

            if (existing) {
                await knex('analyzer_profiles')
                    .where('name', name)
                    .update({
                        configs: JSON.stringify(configs),
                        description,
                        updated_at: knex.fn.now()
                    });
                return { success: true, id: existing.id };
            } else {
                const [id] = await knex('analyzer_profiles').insert({
                    name,
                    configs: JSON.stringify(configs),
                    description
                });
                return { success: true, id };
            }
        } catch (error) {
            console.error('Failed to save profile:', error);
            throw error;
        }
    });

    // Get all profiles
    ipcMain.handle('config:get-profiles', async () => {
        try {
            const rows = await knex('analyzer_profiles').orderBy('updated_at', 'desc');
            return rows.map(row => ({
                ...row,
                configs: JSON.parse(row.configs)
            }));
        } catch (error) {
            console.error('Failed to get profiles:', error);
            throw error;
        }
    });

    // Save AI template
    ipcMain.handle('ai:save-template', async (event, { sceneKey, template }) => {
        try {
            const existing = await knex('ai_prompt_templates').where('scene_key', sceneKey).first();

            if (existing) {
                await knex('ai_prompt_templates')
                    .where('scene_key', sceneKey)
                    .update({
                        template,
                        updated_at: knex.fn.now()
                    });
                return { success: true, id: existing.id };
            } else {
                const [id] = await knex('ai_prompt_templates').insert({
                    scene_key: sceneKey,
                    template
                });
                return { success: true, id };
            }
        } catch (error) {
            console.error('Failed to save AI template:', error);
            throw error;
        }
    });

    // Get AI template
    ipcMain.handle('ai:get-template', async (event, sceneKey) => {
        try {
            const row = await knex('ai_prompt_templates').where('scene_key', sceneKey).first();
            return row;
        } catch (error) {
            console.error('Failed to get AI template:', error);
            throw error;
        }
    });

    // Get storage path configuration
    ipcMain.handle('config:get-storage-path', async () => {
        try {
            const config = await knex('global_configs').where('key', 'storage_path').first();
            if (config) {
                return config.value;
            }
            // Return default path if not configured
            const path = require('path');
            const { app } = require('electron');
            const defaultPath = path.join(app.getPath('userData'), 'cases');
            return defaultPath;
        } catch (error) {
            console.error('Failed to get storage path:', error);
            throw error;
        }
    });

    // Set storage path configuration
    ipcMain.handle('config:set-storage-path', async (event, newPath) => {
        try {
            const fs = require('fs').promises;

            // Validate path is accessible and writable
            try {
                await fs.access(newPath);
                await fs.access(newPath, fs.constants.W_OK);
            } catch (err) {
                throw new Error(`路径无效或无写入权限: ${newPath}`);
            }

            // Update or insert configuration
            const existing = await knex('global_configs').where('key', 'storage_path').first();

            if (existing) {
                await knex('global_configs')
                    .where('key', 'storage_path')
                    .update({
                        value: newPath,
                        updated_at: knex.fn.now()
                    });
            } else {
                await knex('global_configs').insert({
                    key: 'storage_path',
                    value: newPath
                });
            }

            console.log('Storage path updated to:', newPath);
            return { success: true, path: newPath };
        } catch (error) {
            console.error('Failed to set storage path:', error);
            throw error;
        }
    });

    // Get log path configuration
    ipcMain.handle('config:get-log-path', async () => {
        try {
            const config = await knex('global_configs').where('key', 'log_path').first();
            if (config) {
                return config.value;
            }
            // Return default path if not configured
            const path = require('path');
            const { app } = require('electron');
            const defaultPath = path.join(app.getPath('userData'), 'logs');
            return defaultPath;
        } catch (error) {
            console.error('Failed to get log path:', error);
            throw error;
        }
    });

    // Set log path configuration
    ipcMain.handle('config:set-log-path', async (event, newPath) => {
        try {
            const fs = require('fs').promises;

            // Validate path is accessible and writable
            try {
                await fs.access(newPath);
                await fs.access(newPath, fs.constants.W_OK);
            } catch (err) {
                throw new Error(`路径无效或无写入权限: ${newPath}`);
            }

            // Update or insert configuration
            const existing = await knex('global_configs').where('key', 'log_path').first();

            if (existing) {
                await knex('global_configs')
                    .where('key', 'log_path')
                    .update({
                        value: newPath,
                        updated_at: knex.fn.now()
                    });
            } else {
                await knex('global_configs').insert({
                    key: 'log_path',
                    value: newPath
                });
            }

            console.log('Log path updated to:', newPath);
            return { success: true, path: newPath, requiresRestart: true };
        } catch (error) {
            console.error('Failed to set log path:', error);
            throw error;
        }
    });

    // Get log file content
    ipcMain.handle('config:get-log-content', async () => {
        try {
            const fs = require('fs').promises;
            const path = require('path');
            const { app } = require('electron');

            // Get configured log path
            const config = await knex('global_configs').where('key', 'log_path').first();
            let logPath;
            if (config && config.value) {
                logPath = path.join(config.value, 'app.log');
            } else {
                logPath = path.join(app.getPath('userData'), 'app.log');
            }

            // Read last 1000 lines (to avoid loading huge files)
            const content = await fs.readFile(logPath, 'utf8');
            const lines = content.split('\n');
            const recentLines = lines.slice(-1000).join('\n');

            return { content: recentLines, path: logPath };
        } catch (error) {
            console.error('Failed to read log file:', error);
            throw error;
        }
    });
}

module.exports = { registerConfigHandlers };
